package com.lry.netty01.server.processor;

import com.lry.netty01.server.entity.FixedFrame;
import com.lry.netty01.server.utils.ChannelUtil;
import com.lry.netty01.server.utils.CommandUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RegisterRequestProcessor implements RequestProcessor {

    private RequestProcessor next;

    public RegisterRequestProcessor(RequestProcessor next) {
        this.next = next;
    }

    @Override
    public boolean processRequest(Channel channel, FixedFrame fixedFrame) {
        if(fixedFrame.getCmd()== CommandUtil.REGISTER_CMD){
            short devId = fixedFrame.getDevId();
            log.info("收到"+devId+"的注册包");
            Channel cacheChannel = ChannelUtil.online_channels2.get(devId);
            if(ChannelUtil.checkChannel(cacheChannel)){
                log.info(devId+" 挤掉上个设备");
                ChannelUtil.clearCache(devId,cacheChannel);
            }

            ChannelUtil.online_channels2.put(devId,channel);

            ChannelUtil.online_channels.put(channel,devId);

            //回发客户端注册成功指令
            channel.writeAndFlush(fixedFrame);
            return true;
        }else{
            return next.processRequest(channel,fixedFrame);
        }

    }


}
